<?php
// 初始化棋盘
function initChessBoard() {
    $board = array_fill(0, 10, array_fill(0, 9, ''));

    // 红方棋子
    $board[0][0] = '車';
    $board[0][1] = '馬';
    $board[0][2] = '相';
    $board[0][3] = '仕';
    $board[0][4] = '帥';
    $board[0][5] = '仕';
    $board[0][6] = '相';
    $board[0][7] = '馬';
    $board[0][8] = '車';
    $board[2][1] = '炮';
    $board[2][7] = '炮';
    for ($i = 0; $i < 9; $i += 2) {
        $board[3][$i] = '兵';
    }

    // 黑方棋子
    $board[9][0] = '車';
    $board[9][1] = '馬';
    $board[9][2] = '象';
    $board[9][3] = '士';
    $board[9][4] = '將';
    $board[9][5] = '士';
    $board[9][6] = '象';
    $board[9][7] = '馬';
    $board[9][8] = '車';
    $board[7][1] = '炮';
    $board[7][7] = '炮';
    for ($i = 0; $i < 9; $i += 2) {
        $board[6][$i] = '卒';
    }

    return $board;
}

// 获取棋盘 HTML 表格
function getBoardHTML($board) {
    $html = '<table border="1">';
    for ($i = 0; $i < 10; $i++) {
        $html .= '<tr>';
        for ($j = 0; $j < 9; $j++) {
            $html .= '<td width="50" height="50" data-x="' . $j . '" data-y="' . $i . '">';
            $html .= $board[$i][$j];
            $html .= '</td>';
        }
        $html .= '</tr>';
    }
    $html .= '</table>';
    return $html;
}

$board = initChessBoard();
?>

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>中国象棋网页游戏</title>
    <style>
        table {
            border-collapse: collapse;
        }

        td {
            text-align: center;
            font-size: 24px;
        }
    </style>
</head>

<body>
    <h1>中国象棋网页游戏</h1>
    <?php echo getBoardHTML($board); ?>

    <script>
        const cells = document.querySelectorAll('td');
        let selectedPiece = null;

        cells.forEach(cell => {
            cell.addEventListener('click', function () {
                if (selectedPiece === null) {
                    if (this.textContent.trim()!== '') {
                        selectedPiece = this;
                        this.style.backgroundColor = 'yellow';
                    }
                } else {
                    const fromX = parseInt(selectedPiece.dataset.x);
                    const fromY = parseInt(selectedPiece.dataset.y);
                    const toX = parseInt(this.dataset.x);
                    const toY = parseInt(this.dataset.y);

                    // 简单落子逻辑（未实现规则判断）
                    this.textContent = selectedPiece.textContent;
                    selectedPiece.textContent = '';
                    selectedPiece.style.backgroundColor = '';
                    selectedPiece = null;

                    // 这里可添加更多逻辑，如检查落子是否符合规则等
                }
            });
        });
    </script>
</body>

</html>